const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const orderService = require('../../services/good/orderService');
const userService = require('../../services/system/userService');
const couponService = require('../../services/good/couponService');
const goodService = require('../../services/good/goodsService');
class OrderController {
    static async getOrderList(ctx) {
        // 确保请求体存在，如果不存在则初始化为空对象
        const requestData = ctx.request.body || {};
        
        // 解构分页参数，如果未提供则使用默认值
        const { pageNum = 1, pageSize = 10 } = requestData;
        
        // 创建查询数据对象，排除分页参数
        const queryData = { ...requestData };
        delete queryData.pageNum;
        delete queryData.pageSize;
        
        // 添加用户ID到查询条件中
        queryData.userId = ctx.userId;

        try {
            const res = await orderService.getOrderList({ pageNum, pageSize }, queryData);
            response.success(ctx, { data: res });
        } catch (error) {
            response.error(ctx, { message: '获取订单列表失败: ' + error.message });
        }
    }
    static async getOrderById(ctx) {
        const { id: orderId } = ctx.request.body;
        try {
            const res = await orderService.getOrderById(orderId);
            res ? response.success(ctx, { data: res }) : response.error(ctx, { message: '订单不存在' });
        } catch (error) {
            console.error('Error fetching order:', error);
        }

    }
    static async pay(ctx) {
        try {
            const orderinfo = ctx.request.body;
            
            // 验证必要参数
            if (!orderinfo.outTradeNo || !orderinfo.totalAmount || !orderinfo.returnUrl || !orderinfo.payType) {
                return response.error(ctx, { message: '缺少必要参数' });
            }
            
            orderinfo.userId = ctx.userId;

            const user = await userService.getUserById(orderinfo.userId);
            if (!user) {
                return response.error(ctx, { message: '用户不存在' });
            }
            
            // 确保totalAmount是数字类型
            const totalAmount = parseFloat(orderinfo.totalAmount);
            if (isNaN(totalAmount)) {
                return response.error(ctx, { message: '订单金额格式错误' });
            }
            
            if (user.money < totalAmount) {
                return response.error(ctx, { message: '余额不足' });
            }
            
            const res = await orderService.pay(orderinfo);
            if (res) {
                response.success(ctx, { data: res });
            } else {
                response.error(ctx, { message: '生成支付链接失败' });
            }
        } catch (error) {
            response.error(ctx, { message: '支付处理失败: ' + error.message });
        }
    }

    static async successPaid(ctx) {
        const orderinfo = ctx.request.body;
        if (orderinfo.outTradeNo) {
            await orderService.updateOrderStatusById(orderinfo.outTradeNo, 2);
            console.log('修改状态成功')
            await userService.updateUserMoney(orderinfo.userId, -orderinfo.totalAmount);
            console.log('修改余额成功')
            //根据订单id查看使用了那张优惠券
            const order = await orderService.getOrderById(orderinfo.outTradeNo);
            if (order.couponId) {
                await userService.addUserCouponRecord(orderinfo.userId, order.couponId);
                console.log('修改优惠券使用次数成功')
            }
            // await userService.addUserCouponRecord(orderinfo.userId, orderinfo.totalAmount * 0.9);
            response.success(ctx, { message: '支付成功' })
        } else {
            return response.error(ctx, { message: '参数异常' });
        }

    }

    static async createOrder(ctx) {
        try {
            const orderData = ctx.request.body;
            
            // 验证必要字段
            if (!orderData.goodsInfo || !Array.isArray(orderData.goodsInfo) || orderData.goodsInfo.length === 0) {
                return response.error(ctx, { message: '商品信息不能为空' });
            }
            
            // 验证每个商品项的必要字段
            for (const item of orderData.goodsInfo) {
                if (!item.goodId || !item.quantity || !item.sid) {
                    return response.error(ctx, { message: '商品信息不完整' });
                }
                
                // 确保quantity是正整数
                const quantity = parseInt(item.quantity);
                if (isNaN(quantity) || quantity <= 0) {
                    return response.error(ctx, { message: '商品数量必须是正整数' });
                }
                item.quantity = quantity;
            }
            
            // 验证其他必要字段
            if (!orderData.totalPrice || !orderData.estimatedDeliveryTime || !orderData.addressId) {
                return response.error(ctx, { message: '订单信息不完整' });
            }
            
            orderData.userId = ctx.userId;
            
            // 验证优惠券（如果提供了优惠券ID）
            if (orderData.couponId) {
                const coupon = await couponService.getCouponById(orderData.couponId);

                if (coupon) {
                    // 检查优惠券是否在开始时间和结束时间之间
                    const now = new Date();
                    //如果还没开始
                    if (coupon.startTime > now) {
                        return response.error(ctx, { message: '优惠券未开始' });
                    }
                    //如果已经结束
                    if (coupon.endTime < now) {
                        return response.error(ctx, { message: '优惠券已过期' });
                    }

                    let userinfo = await userService.getUserById(orderData.userId)
                    if (!userinfo) {
                        return response.error(ctx, { message: '用户不存在' });
                    }
                    
                    // 检查使用次数限制
                    const userCouponRecord = userinfo.usedCoupons.filter(
                        item => item.couponId.toString() == coupon._id.toString()
                    );

                    const usedCount = userCouponRecord.length
                    if (usedCount >= coupon.limit) {
                        return response.error(ctx, {
                            message: `该优惠券已达到最大使用次数(最多可使用 ${coupon.limit} 次)`
                        });
                    }

                    //检查优惠券是否适用于订单中的商品
                    const goods = await goodService.getGoodsByIds(orderData.goodsInfo.map(item => item.goodId));
                    var aps = coupon.applicableProducts.map(e => e._id.toString())
                    var acs = coupon.applicableCategories.map(e => e._id.toString())

                    const invalidGoods = goods.filter(item => {
                        return !aps.includes(item._id.toString()) &&
                            !acs.includes(item?.categoryId._id.toString());
                    });
                    
                    if (invalidGoods.length > 0) {
                        const invalidDetails = invalidGoods.map(item => {
                            return `${item?.name || '错误商品,请检查'} (ID: ${item._id})`;
                        }).join(', ');

                        // 获取适用的商品ID和类别
                        const applicableProducts = coupon.applicableProducts.map(e => `${e.name}(${e._id})`).join(', ');
                        const applicableCategories = coupon.applicableCategories.map(e => `${e.name}(${e._id})`).join(', ');

                        return response.error(ctx, {
                            message: `优惠券适用商品ID: ${applicableProducts || '错误商品ID,请检查'}\n适用商品类别: ${applicableCategories || '错误类别,请检查'}\n以下商品不适用: ${invalidDetails}`
                        });
                    }
                }
            }
            
            // 创建订单
            const result = await orderService.createOrder(orderData);
            response.success(ctx, { data: result });
        } catch (err) {
            handleDatabaseError(ctx, err, '创建订单失败');
        }
    }
    static async updateOrder(ctx) {
        const orderData = ctx.request.body;
        await orderService.updateOrder(orderData.id, orderData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '订单名称重复'));
    }
    static async deleteOrder(ctx) {
        const { id: orderId } = ctx.request.body;
        const res = await orderService.deleteOrder(orderId);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
    static async updateOrderStatus(ctx) {
        const { outTradeNo, status } = ctx.request.body;
        const res = await orderService.updateOrderStatusById(outTradeNo, status);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
}
module.exports = OrderController;
// This code defines an OrderController class that handles CRUD operations for orders in a good management system.